<template>
  <div>
    <div v-if="isShowChart" ref="chartRef" style="width: 100%; height: 400px" />
    <px-empty v-else description="暂无数据" />
  </div>
</template>
<script lang="ts" setup>
import { ref, watch, onBeforeUnmount } from "vue";
import { http } from "@/utils/http";
import * as echarts from "echarts";
import { correlationFactorMachineApi } from "@/api/machineFreezeHouseAPI";
const chartRef = ref(null);

type ResultTable = {
  total?: number;
  data?: Array<any>;
};

const props = defineProps({
  factors: {
    type: Array,
    default: () => []
  }
});
watch(
  () => props.factors,
  (newValue, oldValue) => {
    if (newValue != null && newValue.length > 0) {
      // getList();
      getUUID();
    }
  }
);

const getList = () => {
  let params = {
    //factorList: ["ACM_F", "Humidity", "FFU_Speed", "Temperature", "AMC_VOC_Ratio", "VOC_VOC7", "AMC_NH3"]
    //数据集来源待确认
    factorList: props.factors
  };
  queryList(params).then(res => {
    createChart(res);
  });
};
//查询SPC指标列表
const queryList = (data?: object) => {
  return http.request<ResultTable>("post", `/operation/api/v1/machine/correlationFactors/queryCorrelationFactorS`, {
    data
  });
};
const isShowChart = ref(false);
const createChart = list => {
  if (list == null || list.length === 0) {
    return;
  }
  list = getRandomList(list); //筛选重复数据
  const option = getOption(list);
  if (chartRef.value) {
    const myChart = echarts.init(chartRef.value);
    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);
  }
};

const getRandomList = list => {
  const types = [];
  const newList = [];
  for (let i = 0; i < list.length; i++) {
    if (!types.includes(list[i].factor)) {
      types.push(list[i].factor);
      const factors = list.filter(p => p.factor == list[i].factor);
      newList.push(factors[Number.parseInt((Math.random() * factors.length).toString())]);
    }
  }
  return newList;
};
const getOption = list => {
  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    grid: {
      bottom: "5%",
      containLabel: true //防止标签溢出
    },
    xAxis: {
      type: "category",
      axisLabel: {
        interval: 0,
        rotate: 45 // 文字倾斜角度
        // formatter: function (value) {
        //     return value.split("").join("\n") //垂直显示
        // },
      },
      data: []
    },
    yAxis: {
      type: "value"
    },
    series: [
      {
        data: [],
        type: "bar"
      }
    ]
  };
  for (let i = 0; i < list.length; i++) {
    option.xAxis.data.push(list[i].factor);
    option.series[0].data.push(list[i].correlationFactors);
  }
  return option;
};

function formatDate(date, type?, monthStart?, monthEnd?) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");

  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  if (type) {
    if (monthStart == "Start") {
      return `${year}-${month}-01 00:00:00`;
    } else {
      return `${year}-${month}-31 23:59:59`;
    }
  } else {
    return `${year}-${month}-${day} ${h}:${m}:${s}`;
  }
}

const cacheRedisPCWAPI = (data?: object) => {
  return http.request<ResultTable>("post", `/operation/api/v1/operation/algorithm/cacheRedisPCW`, {
    data
  });
};
let timerId = null;
// const 获取uuid
const getUUID = async () => {
  try {
    const end = new Date();
    end.setHours(23, 59, 59, 0);
    end.setTime(end.getTime() - 3600 * 1000 * 24 * 1);
    const start = new Date();
    start.setHours(0, 0, 0, 0);
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 31);
    const params = {
      taskType: "",
      midOrLow: "PCW",
      startTime: formatDate(start),
      endTime: formatDate(end)
      // startTime: "2024-12-01 00:00:00",
      // endTime: "2024-12-24 23:59:59"
    };
    isShowChart.value = false;
    const res1 = await correlationFactorMachineApi(params);
    isShowChart.value = true;
    timerId = setInterval(async () => {
      const res2 = await cacheRedisPCWAPI({ uuid: res1 });
      if (res2) {
        createChart(res2);
      }
    }, 6000);
  } catch (error) {}
};

onBeforeUnmount(() => {
  clearInterval(timerId);
});
</script>
